package com.us.simple.sys.service.impl;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.us.simple.sys.entity.UserInfo;
import com.us.simple.sys.mapper.UserInfoMapper;
import com.us.simple.sys.service.IUserInfoService;
import com.us.simple.common.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: wangziqian
 * @Date: 2024-05-15
 *
 */
@Service
@Slf4j
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Override
    public Map<String, Object> login(String username, String password) {
        LambdaQueryWrapper<UserInfo> query = new LambdaQueryWrapper<UserInfo>();
        query.eq(UserInfo::getUsername, username);
        query.eq(UserInfo::getPassWord, password);
        UserInfo login = this.getOne(query);

        if (login == null) {
            throw new RuntimeException("用户名或密码错误!");
        }

        try {
            Map<String, String> payload = new HashMap<>();
            payload.put("userid", String.valueOf(login.getUserId()));
            payload.put("username", login.getUsername());
            // 生成token
            String token = JwtUtil.getToken(payload);
            //redisTemplate.opsForValue().set(adminTokenKey + "-" + userId, jwtToken, 7200, TimeUnit.SECONDS);
            Map map = new HashMap();
            map.put("token", token);
            map.put("userIfo", login);
            return map;
        } catch (Exception e) {
            throw new RuntimeException("登录失败!");
        }

    }

    @Override
    public void logout(HttpServletRequest request) {
        String token = request.getHeader("token");
        DecodedJWT verify = JwtUtil.verify(token);
        String id = verify.getClaim("userid").asString();
        String name = verify.getClaim("username").asString();
        //todo 删除redis缓存
        //两种方式 一种是客户端直接删除token
        // 一种是 jwt结合redis,做过期策略
    }

    @Override
    public Integer getListCount() {
        return userInfoMapper.getListCount();
    }
}
